﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using CSVExportImport.Columns;

namespace CSVExportImport
{
    public class Processor
    {
        public bool Headers { get; set; }
        public bool SortColumsByHeadesOnInport { get; set; }

        public Processor()
        {
            Headers = true;
            SortColumsByHeadesOnInport = true;
        }

        protected List<IColumnTemplate> columns = new List<Columns.IColumnTemplate>();

        public void AddColumn(IColumnTemplate cl)
        {
            columns.Add(cl);
        }

        public void Export(TextWriter writer, IEnumerable collection)
        {
            WriterWrapper output = new WriterWrapper(writer);

            if (Headers)
            {
                foreach (IColumnTemplate col in columns)
                {
                    output.WriteElement(col.Header);
                }
                output.WriteLine();
            }

            foreach (Object obj in collection)
            {
                foreach (IColumnTemplate col in columns)
                {
                    output.WriteElement(col.GetValue(obj));
                }
                output.WriteLine();
            }
        }
        public ICollection Import(TextReader reader, Func<Object> factory)
        {
            ReaderWrapper input = new ReaderWrapper(reader);

            List<Object> res = new List<object>();

            if (Headers)
            {
                Dictionary<String, int> order = new Dictionary<string,int>();
                int c = 1;
                foreach (IColumnTemplate col in columns)
                {
                    order.Add(input.ReadValue(), c++);
                }
                input.AssertNewLine();

                columns.OrderBy(col => order[col.Header]);
            }

            while (!input.EnfOfStreamReached)
            {
                Object obj = factory.Invoke();
                
                foreach (IColumnTemplate col in columns)
                {
                    col.SetValue(obj, input.ReadValue());
                }
                if (!input.EnfOfStreamReached)
                {
                    input.AssertNewLine();
                }

                res.Add(obj);
            }

            return res;
        }
    }
}
